import {TripService} from "../../service/trip";
import {routing} from "../../utils/routing";

const centPerSec = 0.7

function formatDuration(sec: number) {
    const padString = (n: number) => {
        return n < 10 ? '0' + n.toFixed(0) : n.toFixed(0)
    }

    const h = Math.floor(sec / 3600)
    sec -= 3600 * h
    const m = Math.floor(sec / 60)
    sec -= 60 * m
    const s = Math.floor(sec)
    return `${padString(h)}:${padString(m)}:${padString(s)}`
}

function formatFee(cents: number) {
    return (cents / 100).toFixed(2)
}

Page({
    timer: undefined as number | undefined,
    tripId: '',
    updateTripPostTimer: undefined as number | undefined,
    data: {
        latitude: 30.528310553395897,
        longitude: 104.1083129286194,
        scale: 14,
        elapsed: "00:00:00",
        fee: "0.00"
    },

    async onLoad(opt) {
        this.tripId = opt.trip_id as string
        try {
            const trip = await TripService.GetTrip(this.tripId)
            if (!trip){
                await wx.showModal({
                    title:"提醒",
                    content:"获取行程失败",
                    success:()=>{
                        wx.redirectTo({
                            url:"/pages/index/index"
                        })
                    }
                })

                return
            }
            if (trip.status == 2){
                await wx.showModal({
                    title:"行程提醒",
                    content:"当前行程已结束",
                    success:()=>{
                        wx.redirectTo({
                            url:`/pages/mytrips/mytrips`
                        })
                    }
                })
                return
            }
        }catch (e){
            await wx.showModal({
                title:"提醒",
                content:"获取行程失败",
                success:()=>{
                    wx.redirectTo({
                        url:"/pages/index/index"
                    })
                }
            })

            return
        }


        this.setupLocationUpdate()
        // this.setUpTimer()
        this.updateTripPostTimer = setInterval(() => {
            TripService.updateTripPos(this.tripId, {
                latitude: this.data.latitude,
                longitude: this.data.longitude
            }).then((res)=>{
               if (res.currents.length != 0){
                  if (this.timer){
                      clearInterval(this.timer)
                  }
                   this.setData({
                       elapsed: formatDuration(res.currents[res.currents.length -1].timestamp_sec - res.start.timestamp_sec ),
                       fee: formatFee(res.currents[res.currents.length -1].fee_cent | 0)
                   })
               }
            })
        }, 1000)
    },
    onUnload() {
        wx.stopLocationUpdate()
        if (this.timer) {
            clearInterval(this.timer)
        }

        if (this.updateTripPostTimer){
            clearInterval(this.updateTripPostTimer)
        }
    },
    setupLocationUpdate() {
        wx.startLocationUpdate({
            fail: (res) => {
                console.log(res)
            },
            success: (res) => {
                console.log(res)
            }
        })

        wx.onLocationChange((loc) => {
            console.log(loc)
            this.setData({
                latitude: loc.latitude,
                longitude: loc.longitude
            })
        })
    },
    setUpTimer() { // 时间
        let elapsedSed = 0
        let cents = 0
        this.timer = setInterval(() => {
            elapsedSed++
            cents += centPerSec
            this.setData({
                elapsed: formatDuration(elapsedSed),
                fee: formatFee(cents)
            })
        }, 1000)
    },
    onEndTripTap() {

        TripService.finishTrip(this.tripId).then(() => {
            if (this.updateTripPostTimer){
                clearInterval(this.updateTripPostTimer)
            }
            wx.redirectTo({
                url: routing.mytrips(),
            })
        }).catch(err => {
            console.error(err)
            wx.showToast({
                title: '结束行程失败',
                icon: 'none',
            })
        })
    }
})